<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>新闻管理</el-breadcrumb-item>
      <el-breadcrumb-item>新闻列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom: 20px" icon="el-icon-plus" @click="addNews">添加新闻</el-button>
      <el-alert show-icon v-if="isHasNewsTypeId" :title="'这是新闻分类为 '+currentNewsType+' 的新闻~~~'" type="success" close-text="我知道了" style="margin-bottom: 20px"></el-alert>
      <el-alert show-icon v-else title="这是全部新闻~~~" type="success" style="margin-bottom: 20px" close-text="我知道了"></el-alert>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="新闻名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.news_title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="新闻图片" width="180">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="'http://localhost:3001/'+scope.row.news_pic_url" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="新闻分类" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.newstype_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="220">
          <template slot-scope="scope">
            <span>{{ scope.row.news_create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑新闻其它信息</el-button>
            <el-button size="mini" icon="el-icon-edit" type="primary" @click="handleLook(scope.row.news_content,scope.row.newsid)">查看和编辑新闻内容</el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.row.newsid)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 显示新闻详细和编辑新闻内容的内容 -->
    <el-dialog v-on:close="closeContent" v-on:open="openContent" title="查看和编辑新闻内容" :visible.sync="centerDialogVisible" width="45%" center>
      <div class="content"></div>
    </el-dialog>
    <!-- 修改新闻其它信息的表单 -->
    <el-dialog title="编辑新闻其它信息" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="新闻标题" label-width='100px' prop="title">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻分类" label-width='100px' prop="newsTypeId">
          <el-select v-if="NewsTypeOptions.length!==0" filterable v-model="form.newsTypeId" placeholder="请选择">
            <el-option v-for="item in NewsTypeOptions" :key="item.newstypeid" :label="item.newstype_name" :value="item.newstypeid">
            </el-option>
          </el-select>
          <span v-else style="text-decoration:underline;color:#409eff;cursor:pointer;" v-on:click="$router.push('/newstypelist')">请先添加新闻分类！</span>
        </el-form-item>
        <el-form-item label="新闻图片" label-width='100px'>
          <el-upload class="avatar-uploader" :auto-upload="false" action="#" accept="image/*" :multiple="false" :on-change="handleImageChange" :show-file-list="false">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit('ruleForm')">提交</el-button>
      </div>
    </el-dialog>
    <!-- 添加新闻的表单 -->
    <el-dialog title="添加新闻" :visible.sync="dialogFormVisibleAddNews">
      <el-form :model="addForm" :rules="addNewsRules" ref="ruleForm1">
        <el-form-item label="新闻标题" label-width='100px' prop="title">
          <el-input v-model="addForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻分类" label-width='100px' prop="newsTypeId">
          <el-select v-if="NewsTypeOptions.length!==0" filterable v-model="addForm.newsTypeId" placeholder="请选择">
            <el-option  v-for="item in NewsTypeOptions" :key="item.newstypeid" :label="item.newstype_name" :value="item.newstypeid">
            </el-option>
          </el-select>
          <span v-else style="text-decoration:underline;color:#409eff;cursor:pointer;" v-on:click="$router.push('/newstypelist')">请先添加新闻分类！</span>
        </el-form-item>
        <el-form-item label="新闻内容" prop="content">
          <el-input type="textarea" v-model="addForm.content" placeholder="请输入新闻初步编辑的文字(不建议在此处进行全部编辑)！"></el-input>
        </el-form-item>
        <el-form-item label="新闻图片" label-width='100px' prop="picfile">
          <el-upload class="avatar-uploader" :auto-upload="false" action="#" accept="image/*" :multiple="false" :on-change="handleImageChangeAddNews" :show-file-list="false">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitAddNews('ruleForm1')">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNews,
  getNewsByNewsTypeId,
  getNewsTypeById,
  editNewsWithContent,
  deleteNews,
  getNewsType,
  editNewsNoContent,
  addNews
} from '../../utils/api'
export default {
  data () {
    return {
      // 表格数据
      tableData: [],
      // 当前新闻分类的id
      currentNewsTypeId: 0,
      // 是否携带新闻分类
      isHasNewsTypeId: false,
      // 当前的新闻分类名
      currentNewsType: '',
      // 控制显示新闻内容的显示
      centerDialogVisible: false,
      // 新闻内容
      newsContent: '',
      // 当前新闻内容的新闻id
      currentNewsContentId: 0,
      // 输入框
      editor: null,
      // 控制修改新闻其他信息的表单的显示
      dialogFormVisible: false,
      // 修改新闻其它信息的表单
      // id title picfile newsTypeId
      form: {
        id: 0,
        title: '',
        picfile: null,
        newsTypeId: ''
      },
      // 修改新闻其它信息的表单的校验
      rules: {
        title: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' }
        ],
        newsTypeId: [
          { required: true, message: '请选择新闻分类', trigger: 'change' }
        ]
      },
      // 新闻分类列表
      NewsTypeOptions: [],
      imageUrl: '',
      // 控制添加新闻的表单的显示
      dialogFormVisibleAddNews: false,
      // 添加新闻的表单
      // title content picfile create_time newsTypeId
      addForm: {
        title: '',
        picfile: null,
        newsTypeId: '',
        content: ''
      },
      // 添加新闻的表单的校验
      addNewsRules: {
        title: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' }
        ],
        newsTypeId: [
          { required: true, message: '请选择新闻分类', trigger: 'change' }
        ],
        picfile: [
          { required: true, message: '请选择新闻图片', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入新闻初步编辑的文字(不建议在此处进行全部编辑)！', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 如果是从新闻分类跳转过来
    if (this.$route.query.newstypeid) {
      this.currentNewsTypeId = Number(this.$route.query.newstypeid);
      this.isHasNewsTypeId = !this.isHasNewsTypeId;
      // 作为方法的参数传递进行发起请求
      this.getNewsLByNewsType(this.currentNewsTypeId);
    } else {
      // 不是从新闻分类跳转过来 获取全部新闻
      this.getNewsL();
    }
  },
  methods: {
    // 修改新闻准备上传文件的数据
    handleImageChange (file, filelist) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.picfile = filelist[filelist.length - 1].raw;
    },
    // 添加新闻准备上传文件的数据
    handleImageChangeAddNews (file, filelist) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.addForm.picfile = filelist[filelist.length - 1].raw;
    },
    // 获取对应新闻
    async getNewsLByNewsType (id) {
      let res = await getNewsByNewsTypeId(id);
      if (res.status == 0) {
        this.tableData = res.data;
        // 获取当前的新闻类型进行显示
        // 通过getNewsByNewsTypeId获取有数据 正常获取当前的新闻类型进行显示
        if (res.data.length !== 0) {
          this.currentNewsType = res.data[0].newstype_name;
        } else {
          // 通过getNewsByNewsTypeId获取的数据为0  可以在前面的页面传递NewsType名也可以重新根据newstypeid重新发起请求 这里使用后者
          let res1 = await getNewsTypeById(id);
          this.currentNewsType = res1.data[0].newstype_name;
        }
      } else {
        this.$message.error(res.message);
      }
    },
    // 修改新闻
    onSubmit (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          // id title picfile newsTypeId
          var formData = new FormData();
          formData.append('id', this.form.id);
          formData.append('title', this.form.title);
          formData.append('picfile', this.form.picfile);
          formData.append('newsTypeId', this.form.newsTypeId);
          let res = await editNewsNoContent(formData);
          if (res.status == 0) {
            this.$message({
              message: '修改新闻信息成功！',
              type: 'success'
            });
            if (this.isHasNewsTypeId) {
              this.getNewsLByNewsType(this.currentNewsTypeId)
            } else {
              this.getNewsL();
            }
            this.form.title = '';
            this.form.newsTypeId = '';
            this.form.id = 0;
            this.form.picfile = null;
            this.imageUrl = '';
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
    // 添加新闻 准备数据
    addNews () {
      this.dialogFormVisibleAddNews = true;
      this.getNewsTypeL();
    },
    // 添加新闻
    onSubmitAddNews (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisibleAddNews = false;
          // // title content picfile create_time newsTypeId
          var formData = new FormData();
          formData.append('create_time', new Date().toLocaleString());
          formData.append('title', this.addForm.title);
          formData.append('picfile', this.addForm.picfile);
          formData.append('newsTypeId', this.addForm.newsTypeId);
          formData.append('content', this.addForm.content);
          let res = await addNews(formData);
          if (res.status == 0) {
            this.$message({
              message: '添加新闻成功！',
              type: 'success'
            });
            if (this.isHasNewsTypeId) {
              this.getNewsLByNewsType(this.currentNewsTypeId)
            } else {
              this.getNewsL();
            }
            this.addForm.title = '';
            this.addForm.content = '';
            this.addForm.newsTypeId = '';
            this.addForm.picfile = null;
            this.imageUrl = '';
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
    // 获取全部新闻
    async getNewsL () {
      let res = await getNews();
      if (res.status == 0) {
        this.tableData = res.data;
      } else {
        this.$message.error(res.message);
      }
    },
    // 获取新闻分类 为编辑新闻和添加新闻做准备
    async getNewsTypeL () {
      let res = await getNewsType();
      this.NewsTypeOptions = res.data;
    },
    // 编辑新闻 准备数据
    handleEdit (scope) {
      this.getNewsTypeL();
      this.dialogFormVisible = true;
      this.form.id = scope.newsid;
      this.form.title = scope.news_title;
      this.form.newsTypeId = scope.newstype_id;
    },
    // 删除新闻
    handleDelete (id) {
      this.$confirm('此操作将永久删除该新闻, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await deleteNews(id);
        if (res.status == 0) {
          this.$message({
            message: '删除新闻成功！',
            type: 'success'
          });
          if (this.isHasNewsTypeId) {
            this.getNewsLByNewsType(this.currentNewsTypeId)
          } else {
            this.getNewsL();
          }
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 查看和编辑新闻内容
    handleLook (content, id) {
      this.newsContent = content;
      this.currentNewsContentId = id;
      this.centerDialogVisible = true;
    },
    // 显示新闻详细内容
    openContent () {
      this.$nextTick(() => {
        const E = window.wangEditor;
        this.editor = new E('.content')
        this.editor.config.excludeMenus = [
          'emoticon',
          'image',
          'video',
          'table',
          'todo',
        ]
        this.editor.create()
        this.editor.txt.html(this.newsContent)
      })
    },
    // 编辑新闻的详细内容
    async closeContent () {
      let res = await editNewsWithContent(this.currentNewsContentId, this.editor.txt.html())
      if (res.status == 0) {
        this.$message({
          message: '编辑新闻内容成功！',
          type: 'success'
        });
      }
      if (this.isHasNewsTypeId) {
        this.getNewsLByNewsType(this.currentNewsTypeId)
      } else {
        this.getNewsL();
      }
      this.editor.destroy();
    }
  }
}
</script>

<style lang="less" scoped>
  .avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>